// import wepy from '@wepy/core'
import apis from '../apis/apis'
import ENV from '../config/env'
import store from '../store'

const duration = 2000
let showModal = false

function getHost() {
  return ENV.HOST
}

const fetch = {
  async get(url, pdata, contentType = 'application/json') {
    //'application/json', x-www-form-urlencoded // 默认值
    let header = {
      'content-type': contentType
    }
    if (store.state.token) {
      header.authorization = store.state.token
    }
    let host = getHost(url)

    // 发送请求
    let res = await uni.request({
      url: host + url,
      method: 'GET',
      header,
      data: pdata
    })
    if (res[0]) {
      // todo retry
      uni.showToast({
        title: '网络繁忙，请稍候再试',
        icon: 'none',
        duration
      })
      return false
    }
    console.log('fetch.get.url:', host + url)
    console.log('fetch.get.header:', header)
    console.log('fetch.get.res:', res)
    if (res[1] && res[1].statusCode == 200) {
      if (res[1].data) {
        let d = {}
        if (typeof res[1].data == 'string') {
          try {
            d = JSON.parse(res[1].data)
          } catch (error) {
            console.warn('JSON.parse.error:', error)
          }
        } else {
          d = res[1].data
        }
        if (d.code == 0) {
          return d.data || true
        } else if (d.code == -99999) {
          setTimeout(() => {
            fetch.logout(d)
          }, 0)
          return
        } else if (d.code == 10029) {
          setTimeout(() => {
            fetch.inputInfo(d)
          }, 0)
          return
        } else {
          let msg = d.msg ? d.msg : '未知错误'
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          return false
        }
      } else {
        let content =
          res[1].data && res[1].data.msg ? res[1].data.msg : '未知错误'
        console.warn('请求发生错误，msg:', content)
        uni.showToast({
          title: content,
          icon: 'none'
        })
        return false
      }
    } else {
      let title =
        res[1] && res[1].statusCode
          ? `请求错误，错误码:${res[1].statusCode}`
          : '请求错误，请稍候再试'
      uni.showToast({
        title,
        icon: 'none',
        duration
      })
      console.warn(
        '请求发生错误, 状态码为：',
        res[1].statusCode,
        '请求信息：',
        {
          req: arguments,
          res
        },
        'baseUrl:',
        host
      )
      return false
    }
  },
  async post(url, pdata, contentType = 'application/json') {
    //'application/json', // 默认值
    let header = {
      'content-type': contentType
    }
    if (store.state.token) {
      header.authorization = store.state.token
    }
    let host = getHost(url)

    // 发送请求
    let res = await uni.request({
      url: host + url,
      method: 'POST',
      header,
      data: pdata
    })
    if (res[0]) {
      // todo retry
      uni.showToast({
        title: '网络繁忙，请稍候再试',
        icon: 'none',
        duration
      })
      return false
    }
    if (res[1] && res[1].statusCode == 200) {
      if (res[1].data) {
        let d = {}
        if (typeof res[1].data == 'string') {
          try {
            d = JSON.parse(res[1].data)
          } catch (error) {
            console.warn('JSON.parse.error:', error)
          }
        } else {
          d = res[1].data
        }
        if (d.code == 0) {
          return d.data || true
        } else if (d.code == -99999) {
          setTimeout(() => {
            fetch.logout(d)
          }, 0)
          return
        } else if (d.code == 10029) {
          setTimeout(() => {
            fetch.inputInfo(d)
          }, 0)
          return
        } else {
          let msg = d.msg ? d.msg : '未知错误'
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          return false
        }
      } else {
        let content =
          res[1].data && res[1].data.msg ? res[1].data.msg : '未知错误'
        console.warn('请求发生错误，msg:', content)
        uni.showToast({
          title: content,
          icon: 'none'
        })
        return false
      }
    } else {
      let title =
        res[1] && res[1].statusCode
          ? `请求错误，错误码:${res[1].statusCode}`
          : '请求错误，请稍候再试'
      uni.showToast({
        title,
        icon: 'none',
        duration
      })
      console.warn(
        '请求发生错误, 状态码为：',
        res[1].statusCode,
        '请求信息：',
        {
          req: arguments,
          res
        },
        'baseUrl:',
        host
      )
      return false
    }
  },
  async put(url, pdata, contentType = 'application/json') {
    //'application/json', // 默认值
    let header = {
      'content-type': contentType
    }
    if (store.state.token) {
      header.authorization = store.state.token
    }
    let host = getHost(url)

    // 发送请求
    let res = await uni.request({
      url: host + url,
      method: 'PUT',
      header,
      data: pdata
    })
    if (res[0]) {
      // todo retry
      uni.showToast({
        title: '网络繁忙，请稍候再试',
        icon: 'none',
        duration
      })
      return false
    }
    console.log('fetch.put.res:', res)
    if (res[1] && res[1].statusCode == 200) {
      if (res[1].data) {
        let d = {}
        if (typeof res[1].data == 'string') {
          try {
            d = JSON.parse(res[1].data)
          } catch (error) {
            console.warn('JSON.parse.error:', error)
          }
        } else {
          d = res[1].data
        }
        if (d.code == 0) {
          return d.data || true
        } else if (d.code == -99999) {
          setTimeout(() => {
            fetch.logout(d)
          }, 0)
          return
        } else if (d.code == 10029) {
          setTimeout(() => {
            fetch.inputInfo(d)
          }, 0)
          return
        } else {
          let msg = d.msg ? d.msg : '未知错误'
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          return false
        }
      } else {
        let content =
          res[1].data && res[1].data.msg ? res[1].data.msg : '未知错误'
        console.warn('请求发生错误，msg:', content)
        uni.showToast({
          title: content,
          icon: 'none'
        })
        return false
      }
    } else {
      let title =
        res[1] && res[1].statusCode
          ? `请求错误，错误码:${res[1].statusCode}`
          : '请求错误，请稍候再试'
      uni.showToast({
        title,
        icon: 'none',
        duration
      })
      console.warn(
        '请求发生错误, 状态码为：',
        res[1].statusCode,
        '请求信息：',
        {
          req: arguments,
          res
        },
        'baseUrl:',
        host
      )
      return false
    }
  },
  async uploadFile(tempFilePath) {
    console.log('uploadFile.tempFilePath:', tempFilePath)
    return new Promise(resolve => {
      const host = ENV.HOST
      uni.uploadFile({
        url: host + apis.uploadFile,
        header: {
          authorization: store.state.token
        },
        filePath: tempFilePath,
        name: 'file',
        success: res => {
          console.log('uploadFile.res:', res)
          if (res.statusCode == 200 && res.data) {
            let data = ''
            try {
              data = JSON.parse(res.data)
            } catch (error) {
              data = res.data
            }
            if (data && data.code == 0) {
              return resolve(data.data)
            } else if (data.code == -99999) {
              setTimeout(() => {
                fetch.logout(d)
              }, 0)
              return
            } else if (d.code == 10029) {
              setTimeout(() => {
                fetch.inputInfo(d)
              }, 0)
              return
            }
          }
        }
      })
    })
  },
  logout(data) {
    console.log('fetch.logout.data:', data)
    // if (data.showType == 2) {
    //   uni.showModal({
    //     title: data.title,
    //     content: data.msg,
    //     confirmText: '确定',
    //     showCancel: false,
    //     success: function (res) {}
    //   })
    // } else {
    //   uni.showToast({
    //     title: data.msg,
    //     icon: 'none',
    //     mask: true,
    //     duration
    //   })
    // }

    store.commit('setToken', '')
    store.commit('setUserInfo', null)

    if (showModal) {
      return
    }
    showModal = true
    uni.showModal({
      title: '提示',
      content: '未登录或登录失效，立即登录？',
      success: res => {
        if (res.confirm) {
          uni.reLaunch({
            url: '/pages/login'
          })
        }
      },
      complete: res => {
        showModal = false
      }
    })
  },
  inputInfo () {
    if (showModal) {
      return
    }
    showModal = true
    uni.showModal({
      title: '提示',
      content: '需要先完善信息，立即完善？',
      success: res => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/my/profile'
          })
        }
      },
      complete: res => {
        showModal = false
      }
    })
  },
}

export default fetch
